<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>云打印系统</title>
    <style>
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
        .animate-spin {
            animation: spin 1s linear infinite;
        }
        .fade-enter {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 预览容器响应式样式 */
        .preview-container {
            width: 100%;
            max-width: 210mm;
            margin: 0 auto;
            overflow: hidden;
        }

        .preview-content {
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            padding: 20px;
            margin: 10px 0;
            width: 100%;
            min-height: 297mm;
            font-size: 12pt;
            line-height: 1.5;
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow-y: auto;
            resize: none;
            position: relative;
            transform-origin: top left;
        }

        /* 页面分隔线 */
        .page-break {
            border-top: 1px dashed #999;
            margin: 20mm 0;
            position: relative;
        }

        .page-break::after {
            content: attr(data-page);
            position: absolute;
            right: -40px;
            top: -10px;
            background: #f3f4f6;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
        }

        /* 打印样式 */
        @media print {
            @page {
                size: A4;
                margin: 20mm;
            }

            body {
                margin: 0;
                padding: 0;
            }

            .preview-content {
                box-shadow: none;
                margin: 0;
                padding: 0;
                min-height: auto;
            }

            .page-break {
                page-break-after: always;
                border: none;
                margin: 0;
            }

            .page-break::after {
                display: none;
            }

            .no-print {
                display: none !important;
            }
        }

        /* 页面信息显示 */
        .page-info {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: white;
            padding: 8px 16px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            font-size: 14px;
            color: #666;
            z-index: 1000;
        }

        /* 模板选择下拉菜单样式 */
        .template-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
            background-position: right 0.5rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
            padding-right: 2.5rem;
        }

        /* 字体预览 */
        .font-simsun { font-family: SimSun, serif; }
        .font-simhei { font-family: SimHei, sans-serif; }
        .font-microsoft-yahei { font-family: "Microsoft YaHei", sans-serif; }
        .font-kaiti { font-family: KaiTi, serif; }
        .font-fangsong { font-family: FangSong, serif; }

        /* 移动端预览样式 */
        @media screen and (max-width: 768px) {
            .preview-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                padding: 0 10px;
            }
            
            .preview-content {
                min-height: auto;
                font-size: 10pt;
                padding: 10px;
                margin: 5px 0;
            }

            .page-break::after {
                right: -30px;
                font-size: 10px;
            }

            /* 缩放控制器 */
            .zoom-controls {
                position: fixed;
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: white;
                border-radius: 20px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                padding: 5px;
                display: flex;
                gap: 5px;
                z-index: 1000;
            }

            .zoom-controls button {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                border: none;
                background: #f3f4f6;
                color: #374151;
                font-size: 18px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                transition: all 0.2s;
            }

            .zoom-controls button:hover {
                background: #e5e7eb;
            }

            .zoom-controls .zoom-text {
                display: flex;
                align-items: center;
                padding: 0 10px;
                font-size: 14px;
                color: #374151;
            }
        }

        /* 预览弹窗样式 */
        .preview-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            overflow-y: auto;
        }

        .preview-modal.active {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 20px;
        }

        .preview-modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 210mm;
            margin: 20px auto;
            position: relative;
        }

        .preview-modal-header {
            padding: 1rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .preview-modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #6b7280;
            padding: 0.5rem;
            border-radius: 0.375rem;
        }

        .preview-modal-body {
            padding: 1rem;
        }

        /* 打印任务状态样式 */
        .task-status {
            margin-top: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .task-item {
            padding: 10px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .task-item:last-child {
            border-bottom: none;
        }

        .task-status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-pending {
            background-color: #FEF3C7;
            color: #92400E;
        }

        .status-printing {
            background-color: #DBEAFE;
            color: #1E40AF;
        }

        .status-completed {
            background-color: #D1FAE5;
            color: #065F46;
        }

        .status-failed {
            background-color: #FEE2E2;
            color: #991B1B;
        }

        .task-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .task-name {
            font-weight: 500;
        }

        .task-details {
            font-size: 12px;
            color: #6B7280;
        }

        @media (max-width: 640px) {
            .task-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }

        body {
            font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f0f0;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .printer-dialog {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .printer-list {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ccc;
            margin: 10px 0;
        }
        .printer-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            align-items: center;
        }
        .printer-item:hover {
            background-color: #f5f5f5;
        }
        .printer-item.selected {
            background-color: #e3f2fd;
        }
        .printer-icon {
            width: 24px;
            height: 24px;
            margin-right: 10px;
        }
        .printer-info {
            flex-grow: 1;
        }
        .printer-name {
            font-weight: bold;
        }
        .printer-status {
            font-size: 0.9em;
            color: #666;
        }
        .printer-location {
            font-size: 0.9em;
            color: #888;
        }
        .printer-type {
            font-size: 0.9em;
            color: #666;
            margin-left: 10px;
        }
        .printer-details {
            margin-top: 10px;
            padding: 10px;
            background-color: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 4px;
            display: none;
        }
        .printer-details.show {
            display: block;
        }
        .button-group {
            margin-top: 15px;
            text-align: right;
        }
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        .btn-primary {
            background-color: #1976d2;
            color: white;
        }
        .btn-secondary {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
        }
        .btn:hover {
            opacity: 0.9;
        }
        .status-ready {
            color: #4caf50;
        }
        .status-error {
            color: #f44336;
        }
        .status-warning {
            color: #ff9800;
        }
        .upload-section {
            margin-top: 20px;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 4px;
            text-align: center;
        }
        .upload-section.drag-over {
            background-color: #e3f2fd;
            border-color: #1976d2;
        }
        #uploadProgress {
            width: 100%;
            margin-top: 10px;
            display: none;
        }
        .task-list {
            margin-top: 20px;
        }
        .task-item {
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 10px;
            border-radius: 4px;
        }
        .refresh-button {
            background: none;
            border: none;
            color: #1976d2;
            cursor: pointer;
            padding: 5px;
        }
        .refresh-button:hover {
            text-decoration: underline;
        }

        /* 纸张尺寸样式 */
        .paper-a4-portrait {
            width: 210mm;
            height: 297mm;
        }
        .paper-a4-landscape {
            width: 297mm;
            height: 210mm;
        }
        .paper-a5-portrait {
            width: 148mm;
            height: 210mm;
        }
        .paper-a5-landscape {
            width: 210mm;
            height: 148mm;
        }
        .paper-b5-portrait {
            width: 176mm;
            height: 250mm;
        }
        .paper-b5-landscape {
            width: 250mm;
            height: 176mm;
        }
        .paper-letter-portrait {
            width: 216mm;
            height: 279mm;
        }
        .paper-letter-landscape {
            width: 279mm;
            height: 216mm;
        }

        /* 预览容器样式 */
        #previewContainer {
            transform-origin: top center;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        #previewContent {
            padding: 20mm;
            background-color: white;
            min-height: 100%;
            box-sizing: border-box;
            overflow: auto;
        }

        /* 打印样式 */
        @media print {
            @page {
                margin: 0;
            }
            body * {
                visibility: hidden;
            }
            #previewContent, #previewContent * {
                visibility: visible;
            }
            #previewContent {
                position: absolute;
                left: 0;
                top: 0;
            }
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <div class="max-w-2xl mx-auto">
            <!-- 头部 -->
            <div class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">云打印系统V1.0</h1>
                <p class="text-gray-600">老打印机秒变无线打印机，手机也能打印</p>
            </div>

            <!-- 打印选项卡 -->
            <div class="bg-white rounded-lg shadow mb-8">
                <div class="border-b border-gray-200">
                    <nav class="flex" aria-label="Tabs">
                        <button onclick="switchMode('text')" id="textBtn"
                            class="flex-1 py-4 px-4 text-center border-b-2 font-medium text-sm focus:outline-none">
                            文本打印
                        </button>
                        <button onclick="switchMode('file')" id="fileBtn"
                            class="flex-1 py-4 px-4 text-center border-b-2 font-medium text-sm focus:outline-none">
                            文件打印
                        </button>
                    </nav>
                </div>

                <!-- 文本打印表单 -->
                <form id="textForm" onsubmit="submitForm(event, 'text')" class="p-6 space-y-4">
                    <!-- 基本设置 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="paperSize" class="block text-sm font-medium text-gray-700 mb-2">纸张大小</label>
                            <select id="paperSize" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="A4" selected>A4 (210×297mm)</option>
                                <option value="A5">A5 (148×210mm)</option>
                                <option value="B5">B5 (176×250mm)</option>
                                <option value="Letter">Letter (216×279mm)</option>
                            </select>
                        </div>
                        <div>
                            <label for="orientation" class="block text-sm font-medium text-gray-700 mb-2">打印方向</label>
                            <select id="orientation" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="portrait" selected>纵向</option>
                                <option value="landscape">横向</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="textFont" class="block text-sm font-medium text-gray-700 mb-2">字体</label>
                            <select id="textFont" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="microsoft-yahei">微软雅黑</option>
                                <option value="simsun">宋体</option>
                                <option value="simhei">黑体</option>
                                <option value="kaiti">楷体</option>
                                <option value="fangsong">仿宋</option>
                            </select>
                        </div>
                        <div>
                            <label for="fontSize" class="block text-sm font-medium text-gray-700 mb-2">字号</label>
                            <select id="fontSize" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="10">10pt</option>
                                <option value="12" selected>12pt</option>
                                <option value="14">14pt</option>
                                <option value="16">16pt</option>
                                <option value="18">18pt</option>
                                <option value="20">20pt</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="lineHeight" class="block text-sm font-medium text-gray-700 mb-2">行距</label>
                            <select id="lineHeight" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="1">1.0</option>
                                <option value="1.15" selected>1.15</option>
                                <option value="1.5">1.5</option>
                                <option value="2">2.0</option>
                            </select>
                        </div>
                        <div>
                            <label for="textAlign" class="block text-sm font-medium text-gray-700 mb-2">对齐方式</label>
                            <select id="textAlign" class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                <option value="left">左对齐</option>
                                <option value="center">居中</option>
                                <option value="right">右对齐</option>
                                <option value="justify">两端对齐</option>
                            </select>
                        </div>
                    </div>

                    <!-- 文本输入 -->
                    <div class="space-y-4">
                        <div>
                            <div class="flex justify-between items-center mb-2">
                                <label for="text" class="block text-sm font-medium text-gray-700">输入文本</label>
                                <span id="wordCount" class="text-xs text-gray-500">0 字</span>
                            </div>
                            <textarea id="text" name="text" rows="10" 
                                class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                placeholder="在此输入要打印的文本..."
                                onInput="updateWordCount()"></textarea>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="flex space-x-4">
                            <button type="button" onclick="clearText()" 
                                class="flex-1 bg-gray-600 text-white py-2 px-4 rounded-lg hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors">
                                <svg class="w-5 h-5 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                </svg>
                                清空内容
                            </button>
                            <button type="button" onclick="showPreview()"
                                class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors">
                                <svg class="w-5 h-5 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                </svg>
                                打印预览
                            </button>
                            <button type="button" onclick="confirmPrint()"
                                class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors">
                                <svg class="w-5 h-5 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                                </svg>
                                确认打印
                            </button>
                        </div>
                    </div>
                </form>

                <!-- 预览模态框 -->
                <div id="previewModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 overflow-auto">
                    <div class="absolute inset-4 md:inset-10 bg-white rounded-lg shadow-xl flex flex-col">
                        <div class="flex justify-between items-center p-4 border-b">
                            <h3 class="text-lg font-medium">打印预览</h3>
                            <div class="flex items-center space-x-4">
                                <div class="flex items-center space-x-2">
                                    <button onclick="adjustZoom('out')" class="p-1 hover:bg-gray-100 rounded">
                                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/>
                                        </svg>
                                    </button>
                                    <span id="zoomLevel" class="text-sm">100%</span>
                                    <button onclick="adjustZoom('in')" class="p-1 hover:bg-gray-100 rounded">
                                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                        </svg>
                                    </button>
                                </div>
                                <button onclick="closePreview()" class="text-gray-500 hover:text-gray-700">
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <div class="flex-1 overflow-auto p-4 bg-gray-100">
                            <div id="previewContainer" class="relative bg-white shadow-lg mx-auto">
                                <div id="previewContent" class="absolute inset-0"></div>
                            </div>
                        </div>
                        <div class="p-4 border-t flex justify-between items-center">
                            <span id="pageInfo" class="text-sm text-gray-500">第 1 页 / 共 1 页</span>
                            <div class="flex space-x-4">
                                <button onclick="closePreview()" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                                    关闭预览
                                </button>
                                <button onclick="printFromPreview(event)" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
                                    确认打印
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 文件打印表单 -->
                <form id="fileForm" onsubmit="submitForm(event, 'file')" class="hidden p-6 space-y-4" style="display: none;">
                    <div class="space-y-4">
                        <!-- 文件上传区域 -->
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer" 
                             id="dropZone" 
                             onclick="document.getElementById('fileInput').click()"
                             ondrop="handleDrop(event)" 
                             ondragover="handleDragOver(event)" 
                             ondragleave="handleDragLeave(event)">
                            <input type="file" 
                                   id="fileInput" 
                                   class="hidden" 
                                   accept=".doc,.docx,.pdf,.txt,.jpg,.png,.gif,.jpeg"
                                   onchange="handleFileSelect(event)">
                            <div class="space-y-2">
                                <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                                    <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                </svg>
                                <div class="text-sm text-gray-600">
                                    <span class="font-medium text-blue-600 hover:text-blue-500">点击选择文件</span>
                                    <span class="text-gray-500">或将文件拖放到此处</span>
                                </div>
                                <p class="text-xs text-gray-500">支持的文件格式：PDF、Word文档、文本文件、图片</p>
                            </div>
                        </div>

                        <!-- 文件选择状态显示 -->
                        <div id="fileSelectStatus" class="hidden mt-4">
                            <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                                <div class="flex items-center space-x-4">
                                    <div class="flex-shrink-0">
                                        <svg class="w-8 h-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                        </svg>
                                    </div>
                                    <div>
                                        <p id="selectedFileName" class="text-sm font-medium text-gray-900"></p>
                                        <p id="selectedFileSize" class="text-sm text-gray-500"></p>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <button onclick="cancelFileSelect()" class="px-3 py-1 text-sm text-gray-600 hover:text-gray-800">
                                        取消
                                    </button>
                                    <button onclick="uploadSelectedFile()" id="uploadButton" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
                                        发送文件
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 上传状态显示 -->
                        <div id="uploadStatus" class="hidden mt-4"></div>
                    </div>
                </form>
            </div>

            <!-- 打印任务列表 -->
            <div class="mt-8 bg-white rounded-lg shadow">
                <div class="px-4 py-3 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h2 class="text-lg font-medium text-gray-900">打印任务列表</h2>
                        <button onclick="refreshFileList()" class="text-blue-600 hover:text-blue-800">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                        </button>
                    </div>
                </div>
                <div id="taskList" class="divide-y divide-gray-200">
                    <!-- 任务列表将通过 JavaScript 动态填充 -->
                    <div class="p-4 text-center text-gray-500">
                        正在加载...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentMode = 'text';
        let uploadedFiles = [];
        let cachedPrinters = null;
        let lastPrinterRefresh = null;
        let currentZoom = 100;
        const MIN_ZOOM = 50;
        const MAX_ZOOM = 200;
        const ZOOM_STEP = 10;

        // 切换打印模式
        function switchMode(mode) {
            currentMode = mode;
            document.getElementById('textForm').style.display = mode === 'text' ? 'block' : 'none';
            document.getElementById('fileForm').style.display = mode === 'file' ? 'block' : 'none';
            
            // 更新按钮样式
            document.getElementById('textBtn').className = `flex-1 py-4 px-4 text-center border-b-2 font-medium text-sm focus:outline-none ${mode === 'text' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'}`;
            document.getElementById('fileBtn').className = `flex-1 py-4 px-4 text-center border-b-2 font-medium text-sm focus:outline-none ${mode === 'file' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'}`;
        }

        // 处理文件选择
        async function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            // 检查文件类型
            const allowedTypes = ['.pdf', '.doc', '.docx', '.txt', '.jpg', '.png', '.gif', '.jpeg'];
            const fileExt = '.' + file.name.split('.').pop().toLowerCase();
            if (!allowedTypes.includes(fileExt)) {
                Swal.fire({
                    icon: 'error',
                    title: '不支持的文件类型',
                    text: '请选择 PDF、Word 文档、文本文件或图片'
                });
                event.target.value = ''; // 清空文件选择
                return;
            }

            // 显示文件选择状态
            const fileSelectStatus = document.getElementById('fileSelectStatus');
            const selectedFileName = document.getElementById('selectedFileName');
            const selectedFileSize = document.getElementById('selectedFileSize');
            const uploadButton = document.getElementById('uploadButton');
            
            fileSelectStatus.classList.remove('hidden');
            selectedFileName.textContent = file.name;
            selectedFileSize.textContent = formatFileSize(file.size);
            uploadButton.disabled = false;
        }

        // 取消文件选择
        function cancelFileSelect() {
            document.getElementById('fileInput').value = '';
            document.getElementById('fileSelectStatus').classList.add('hidden');
            document.getElementById('uploadStatus').classList.add('hidden');
        }

        // 上传选择的文件
        async function uploadSelectedFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                Swal.fire({
                    icon: 'warning',
                    title: '请选择文件',
                    text: '请先选择要上传的文件'
                });
                return;
            }

            const uploadButton = document.getElementById('uploadButton');
            const originalText = uploadButton.innerHTML;
            uploadButton.disabled = true;
            uploadButton.innerHTML = `
                <svg class="animate-spin -ml-1 mr-2 h-5 w-5 text-white inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                正在上传...
            `;

            try {
                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    // 显示上传成功状态
                    const uploadStatus = document.getElementById('uploadStatus');
                    uploadStatus.classList.remove('hidden');
                    uploadStatus.innerHTML = `
                        <div class="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                            <div class="flex items-center space-x-4">
                                <div class="flex-shrink-0">
                                    <svg class="w-8 h-8 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-green-800">上传成功: ${file.name}</p>
                                </div>
                            </div>
                            <button onclick="showPrinterDialog('${result.filename}', '${result.original_filename}')" 
                                    class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                                </svg>
                                打印
                            </button>
                        </div>
                    `;
                    
                    // 清空文件选择
                    fileInput.value = '';
                    document.getElementById('fileSelectStatus').classList.add('hidden');
                    uploadButton.disabled = true;
                    uploadButton.innerHTML = originalText;

                    // 刷新文件列表
                    await refreshFileList();
                } else {
                    throw new Error(result.message || '上传失败');
                }
            } catch (error) {
                console.error('文件上传错误:', error);
                const uploadStatus = document.getElementById('uploadStatus');
                uploadStatus.classList.remove('hidden');
                uploadStatus.innerHTML = `
                    <div class="flex items-center justify-between p-4 bg-red-50 rounded-lg">
                        <div class="flex items-center space-x-4">
                            <div class="flex-shrink-0">
                                <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                </svg>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-red-800">上传失败: ${file.name}</p>
                                <p class="text-xs text-red-700">${error.message}</p>
                            </div>
                        </div>
                    </div>
                `;
                uploadButton.disabled = false;
                uploadButton.innerHTML = originalText;
            }
        }

        // 处理文件拖放
        function handleDrop(event) {
            event.preventDefault();
            event.stopPropagation();
            
            const dropZone = document.getElementById('dropZone');
            dropZone.classList.remove('border-blue-500', 'bg-blue-50');
            
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                const fileInput = document.getElementById('fileInput');
                fileInput.files = files;
                handleFileSelect({ target: fileInput });
            }
        }

        function handleDragOver(event) {
            event.preventDefault();
            event.stopPropagation();
            const dropZone = document.getElementById('dropZone');
            dropZone.classList.add('border-blue-500', 'bg-blue-50');
        }

        function handleDragLeave(event) {
            event.preventDefault();
            event.stopPropagation();
            const dropZone = document.getElementById('dropZone');
            dropZone.classList.remove('border-blue-500', 'bg-blue-50');
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 刷新文件列表
        async function refreshFileList() {
            const taskList = document.getElementById('taskList');
            if (!taskList) {
                console.error('任务列表容器不存在');
                return;
            }

            // 显示加载状态
            taskList.innerHTML = `
                <div class="p-4 text-center text-gray-500">
                    <svg class="animate-spin h-5 w-5 mx-auto mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    正在加载...
                </div>
            `;

            try {
                const response = await fetch('/files');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                if (!data.success) {
                    throw new Error(data.error || '获取文件列表失败');
                }

                if (!data.files || data.files.length === 0) {
                    taskList.innerHTML = `
                        <div class="p-4 text-center text-gray-500">
                            暂无打印任务
                        </div>
                    `;
                    return;
                }

                // 按上传时间降序排序
                data.files.sort((a, b) => new Date(b.upload_time) - new Date(a.upload_time));

                // 清空列表
                taskList.innerHTML = '';

                // 添加文件项
                data.files.forEach(file => {
                    const taskItem = document.createElement('div');
                    taskItem.className = 'p-4 hover:bg-gray-50';
                    
                    const statusStyle = getStatusStyle(file.status);
                    
                    taskItem.innerHTML = `
                        <div class="flex items-center justify-between">
                            <div class="flex-1">
                                <div class="flex items-center">
                                    <svg class="w-5 h-5 text-gray-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                                    </svg>
                                    <div>
                                        <div class="font-medium text-gray-900">${file.original_filename}</div>
                                        <div class="text-sm text-gray-500">
                                            上传时间: ${new Date(file.upload_time).toLocaleString()}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="flex items-center space-x-4">
                                <span class="px-2 py-1 text-sm rounded-full ${statusStyle.bg} ${statusStyle.text}">
                                    ${getStatusText(file.status)}
                                </span>
                                ${file.status !== 'printed' ? `
                                    <button onclick="showPrinterDialog('${file.filename}', '${file.original_filename}')" 
                                        class="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                        打印
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    `;
                    taskList.appendChild(taskItem);
                });

            } catch (error) {
                console.error('刷新文件列表失败:', error);
                taskList.innerHTML = `
                    <div class="p-4 text-center text-red-500">
                        <svg class="w-6 h-6 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        获取文件列表失败: ${error.message}
                    </div>
                `;
            }
        }

        // 获取状态样式
        function getStatusStyle(status) {
            const styles = {
                'uploaded': {
                    bg: 'bg-blue-100',
                    text: 'text-blue-800'
                },
                'printed': {
                    bg: 'bg-green-100',
                    text: 'text-green-800'
                },
                'failed': {
                    bg: 'bg-red-100',
                    text: 'text-red-800'
                }
            };
            return styles[status] || styles['uploaded'];
        }

        // 获取状态文本
        function getStatusText(status) {
            const texts = {
                'uploaded': '待打印',
                'printed': '已打印',
                'failed': '打印失败'
            };
            return texts[status] || '未知状态';
        }

        // 页面加载时刷新文件列表
        document.addEventListener('DOMContentLoaded', () => {
            refreshFileList();
            // 每30秒自动刷新一次
            setInterval(refreshFileList, 30000);
        });

        // 获取打印机列表
        async function getPrinterList(forceRefresh = false) {
            if (!forceRefresh && cachedPrinters) {
                return cachedPrinters;
            }

            try {
                const response = await fetch('/printers');
                if (!response.ok) {
                    throw new Error('获取打印机列表失败');
                }
                const printers = await response.json();
                cachedPrinters = printers;
                lastPrinterRefresh = Date.now();
                return printers;
            } catch (error) {
                console.error('获取打印机列表错误:', error);
                throw error;
            }
        }

        // 显示打印机选择对话框
        async function showPrinterDialog(filename, originalFilename) {
            console.log(`开始打印请求 - 文件名: ${filename}, 原始文件名: ${originalFilename}`);
            
            try {
                // 显示加载状态
                Swal.fire({
                    title: '正在获取打印机列表',
                    text: '请稍候...',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    allowEnterKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                const response = await fetch('/printers');
                const data = await response.json();
                console.log('打印机列表响应:', data);

                // 关闭加载状态
                Swal.close();

                if (data.error) {
                    // 如果是打印服务未运行，提供重启选项
                    if (data.error.includes('打印服务未运行')) {
                        const result = await Swal.fire({
                            icon: 'warning',
                            title: '打印服务未运行',
                            text: '打印服务未运行，是否尝试启动服务？',
                            showCancelButton: true,
                            confirmButtonText: '启动服务',
                            cancelButtonText: '取消'
                        });

                        if (result.isConfirmed) {
                            // 尝试启动打印服务
                            try {
                                await fetch('/start_print_service', {
                                    method: 'POST'
                                });
                                // 服务启动后重试获取打印机列表
                                showPrinterDialog(filename, originalFilename);
                                return;
                            } catch (err) {
                                Swal.fire({
                                    icon: 'error',
                                    title: '启动服务失败',
                                    text: '无法启动打印服务，请尝试手动启动或联系管理员。'
                                });
                                return;
                            }
                        } else {
                            return;
                        }
                    } else {
                        // 其他错误
                        Swal.fire({
                            icon: 'error',
                            title: '无法获取打印机',
                            text: data.error
                        });
                        return;
                    }
                }

                if (!data.printers || data.printers.length === 0) {
                    Swal.fire({
                        icon: 'error',
                        title: '未找到打印机',
                        text: '系统中未安装任何打印机，请先安装打印机驱动程序。'
                    });
                    return;
                }

                // 构建打印机选项
                let printerOptions = '';
                data.printers.forEach((printer, index) => {
                    const isDefault = printer.is_default ? ' (默认)' : '';
                    const status = printer.is_ready ? '就绪' : '未就绪';
                    printerOptions += `<option value="${printer.name}" ${printer.is_default ? 'selected' : ''}>${printer.name}${isDefault} - ${status}</option>`;
                });

                // 显示打印设置表单
                const { value: formValues } = await Swal.fire({
                    title: '打印设置',
                    html: `
                        <form id="printSettingsForm" class="space-y-4 text-left">
                            <div>
                                <label for="printer" class="block text-sm font-medium text-gray-700">选择打印机</label>
                                <select id="printer" name="printer" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                    ${printerOptions}
                                </select>
                            </div>
                            <div>
                                <label for="copies" class="block text-sm font-medium text-gray-700">打印份数</label>
                                <input type="number" id="copies" name="copies" min="1" max="10" value="1" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                            </div>
                            <div>
                                <label for="pageRange" class="block text-sm font-medium text-gray-700">打印页面 (例如: 1-5,8,11-13)</label>
                                <input type="text" id="pageRange" name="pageRange" placeholder="全部页面" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                            </div>
                            <div>
                                <label for="orientation" class="block text-sm font-medium text-gray-700">页面方向</label>
                                <select id="orientation" name="orientation" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                    <option value="portrait">纵向</option>
                                    <option value="landscape">横向</option>
                                </select>
                            </div>
                            <div>
                                <label for="pagesPerSheet" class="block text-sm font-medium text-gray-700">每张纸页数</label>
                                <select id="pagesPerSheet" name="pagesPerSheet" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                    <option value="1">1页</option>
                                    <option value="2">2页</option>
                                    <option value="4">4页</option>
                                    <option value="6">6页</option>
                                    <option value="9">9页</option>
                                </select>
                            </div>
                            <div class="flex items-center">
                                <input type="checkbox" id="collate" name="collate" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                <label for="collate" class="ml-2 block text-sm text-gray-700">逐份打印</label>
                            </div>
                            <div class="flex items-center">
                                <input type="checkbox" id="duplex" name="duplex" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                <label for="duplex" class="ml-2 block text-sm text-gray-700">双面打印</label>
                            </div>
                            <div class="italic text-xs text-gray-500 mt-2">注: 部分设置仅对支持的文档类型有效</div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: '打印',
                    cancelButtonText: '取消',
                    showLoaderOnConfirm: true,
                    preConfirm: () => {
                        const form = document.getElementById('printSettingsForm');
                        return {
                            printer: form.printer.value,
                            copies: parseInt(form.copies.value) || 1,
                            pageRange: form.pageRange.value,
                            orientation: form.orientation.value,
                            pagesPerSheet: parseInt(form.pagesPerSheet.value) || 1,
                            collate: form.collate.checked,
                            duplex: form.duplex.checked
                        };
                    }
                });

                if (formValues) {
                    try {
                        // 显示打印中状态
                        await Swal.fire({
                            title: '正在发送打印请求',
                            text: '请稍候...',
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            allowEnterKey: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });

                        console.log('准备发送打印请求:', {
                            filename,
                            originalFilename,
                            printer: formValues.printer,
                            settings: {
                                copies: formValues.copies,
                                page_range: formValues.pageRange,
                                orientation: formValues.orientation,
                                pages_per_sheet: formValues.pagesPerSheet,
                                collate: formValues.collate,
                                duplex: formValues.duplex
                            }
                        });

                        // 发送打印请求
                        const response = await fetch('/print_file', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                filename: filename,
                                original_filename: originalFilename,
                                printer: formValues.printer,
                                settings: {
                                    copies: formValues.copies,
                                    page_range: formValues.pageRange,
                                    orientation: formValues.orientation,
                                    pages_per_sheet: formValues.pagesPerSheet,
                                    collate: formValues.collate,
                                    duplex: formValues.duplex
                                }
                            })
                        });

                        // 检查网络错误
                        if (!response.ok) {
                            const statusText = response.statusText || '未知错误';
                            console.error(`HTTP错误: ${response.status} - ${statusText}`);
                            
                            // 保存更详细的错误信息
                            await saveErrorLog('网络错误', {
                                status: response.status,
                                statusText: statusText,
                                printer: formValues.printer,
                                filename: filename
                            });
                            
                            throw new Error(`服务器返回错误: ${response.status} ${statusText}`);
                        }

                        const resultText = await response.text();
                        console.log('打印响应原始文本:', resultText);
                        
                        let result;
                        try {
                            result = JSON.parse(resultText);
                            console.log('打印响应解析后:', result);
                        } catch (err) {
                            console.error('解析响应JSON失败:', err);
                            console.log('无法解析的响应:', resultText);
                            
                            // 尝试直接从文本响应中判断成功/失败
                            const isSuccess = resultText.includes('success') && resultText.includes('true');
                            result = {
                                success: isSuccess,
                                message: resultText
                            };
                        }
                        
                        // 记录详细的打印请求信息和结果，帮助诊断问题
                        console.log('打印请求详情:', {
                            printer: formValues.printer,
                            filename: filename,
                            原始文件名: originalFilename,
                            设置: formValues,
                            结果: result
                        });
                        
                        // 关闭加载状态
                        await Swal.close();

                        if (result.success) {
                            // 显示成功消息
                            Swal.fire({
                                icon: 'success',
                                title: '打印成功',
                                text: '文件已成功发送到打印机，请检查打印机输出。'
                            });
                            // 刷新文件列表以显示更新的状态
                            setTimeout(refreshFileList, 1000);
                        } else {
                            // 显示错误消息
                            const errorMessage = result.message || '未知错误';
                            console.error('打印失败:', errorMessage);
                            
                            // 保存错误日志
                            await saveErrorLog('打印失败', {
                                printer: formValues.printer,
                                filename: filename,
                                message: errorMessage
                            });
                            
                            Swal.fire({
                                icon: 'error',
                                title: '打印失败',
                                text: errorMessage,
                                footer: '<a href="#" onclick="showPrintTroubleshooting()">查看打印故障排除指南</a>'
                            });
                        }
                    } catch (error) {
                        console.error('处理打印请求时出错:', error);
                        
                        // 保存错误日志
                        await saveErrorLog('打印请求处理错误', {
                            error: error.message,
                            printer: formValues.printer,
                            filename: filename
                        });
                        
                        Swal.fire({
                            icon: 'error',
                            title: '打印请求失败',
                            text: error.message,
                            footer: '<a href="#" onclick="showPrintTroubleshooting()">查看打印故障排除指南</a>'
                        });
                    }
                }
            } catch (error) {
                console.error('显示打印对话框时出错:', error);
                Swal.fire({
                    icon: 'error',
                    title: '无法显示打印对话框',
                    text: error.message
                });
            }
        }

        // 初始化页面
        function init() {
            // 设置默认模式
            switchMode('text');
            
            // 绑定页面范围选择事件
            document.addEventListener('change', function(e) {
                if (e.target.name === 'pageRange') {
                    const customRangeInput = document.getElementById('customRange');
                    if (customRangeInput) {
                        customRangeInput.disabled = e.target.value !== 'custom';
                    }
                }
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);

        // 设置拖放功能
        function setupDragAndDrop() {
            const dropZone = document.getElementById('dropZone');

            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            dropZone.addEventListener('dragenter', () => {
                dragCounter++;
                dropZone.classList.add('border-blue-500', 'bg-blue-50');
            });

            dropZone.addEventListener('dragleave', () => {
                dragCounter--;
                if (dragCounter === 0) {
                    dropZone.classList.remove('border-blue-500', 'bg-blue-50');
                }
            });

            dropZone.addEventListener('drop', async (e) => {
                dragCounter = 0;
                dropZone.classList.remove('border-blue-500', 'bg-blue-50');
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    const input = document.getElementById('file');
                    input.files = files;
                    await handleFileSelect(input);
                }
            });
        }

        // 应用模板
        function applyTemplate() {
            const templateId = document.getElementById('template').value;
            if (!templateId) {
                document.getElementById('text').value = '';
                resetStyle();
                return;
            }

            const template = CONFIG.templates[templateId];
            if (template) {
                document.getElementById('text').value = template.content;
                document.getElementById('textFont').value = template.style.font;
                document.getElementById('fontSize').value = template.style.size;
                document.getElementById('lineHeight').value = template.style.lineHeight;
                document.getElementById('textAlign').value = template.style.align;
            }
        }

        // 重置样式
        function resetStyle() {
            document.getElementById('textFont').value = 'microsoft-yahei';
            document.getElementById('fontSize').value = '12';
            document.getElementById('lineHeight').value = '1.15';
            document.getElementById('textAlign').value = 'left';
        }

        // 清空文本
        function clearText() {
            const textArea = document.getElementById('text');
            if (textArea) {
                textArea.value = '';
                const wordCount = document.getElementById('wordCount');
                if (wordCount) {
                    wordCount.textContent = '0 字';
                }
            }
        }

        // 更新预览
        function updatePreview() {
            const text = document.getElementById('text').value;
            const font = document.getElementById('textFont').value;
            const fontSize = document.getElementById('fontSize').value;
            const lineHeight = document.getElementById('lineHeight').value;
            const textAlign = document.getElementById('textAlign').value;

            // 更新字数统计
            const wordCount = text.replace(/\s/g, '').length;
            document.getElementById('wordCount').textContent = `${wordCount} 字`;

            // 更新预览样式和内容
            const preview = document.getElementById('preview');
            preview.style.fontFamily = getFontFamily(font);
            preview.style.fontSize = `${fontSize}pt`;
            preview.style.lineHeight = lineHeight;
            preview.style.textAlign = textAlign;
            preview.innerHTML = text.replace(/\n/g, '<br>');
        }

        // 计算页数
        function calculatePages() {
            const fullPreview = document.getElementById('fullPreview');
            const previewHeight = fullPreview.scrollHeight;
            const pageHeight = 1122; // A4 高度 (px)
            const totalPages = Math.ceil(previewHeight / pageHeight);
            
            document.getElementById('pageCount').textContent = `第 1 页 / 共 ${totalPages} 页`;
        }

        // 显示全屏预览
        function showPreview() {
            const text = document.getElementById('text').value;
            if (!text.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入文本',
                    text: '请输入要打印的文本内容'
                });
                return;
            }

            try {
                // 获取所有设置
                const paperSize = document.getElementById('paperSize').value;
                const orientation = document.getElementById('orientation').value;
                const font = document.getElementById('textFont').value;
                const fontSize = document.getElementById('fontSize').value;
                const lineHeight = document.getElementById('lineHeight').value;
                const textAlign = document.getElementById('textAlign').value;

                // 设置预览容器尺寸和样式
                const container = document.getElementById('previewContainer');
                container.className = `paper-${paperSize.toLowerCase()}-${orientation}`;
                
                // 设置预览内容样式
                const content = document.getElementById('previewContent');
                content.style.fontFamily = getFontFamily(font);
                content.style.fontSize = `${fontSize}pt`;
                content.style.lineHeight = lineHeight;
                content.style.textAlign = textAlign;
                content.innerHTML = text.replace(/\n/g, '<br>');

                // 显示预览模态框
                document.getElementById('previewModal').classList.remove('hidden');
                
                // 重置缩放
                currentZoom = 100;
                updateZoom();
                
                // 计算页数
                setTimeout(calculatePages, 100); // 等待内容渲染完成
            } catch (error) {
                console.error('预览失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '预览失败',
                    text: '生成预览时出错，请重试'
                });
            }
        }

        // 关闭预览
        function closePreview() {
            document.getElementById('previewModal').classList.add('hidden');
        }

        // 调整缩放
        function adjustZoom(direction) {
            if (direction === 'in' && currentZoom < MAX_ZOOM) {
                currentZoom += ZOOM_STEP;
            } else if (direction === 'out' && currentZoom > MIN_ZOOM) {
                currentZoom -= ZOOM_STEP;
            }
            
            document.getElementById('zoomLevel').textContent = `${currentZoom}%`;
            document.getElementById('fullPreview').style.transform = `scale(${currentZoom / 100})`;
            document.getElementById('fullPreview').style.transformOrigin = 'top left';
        }

        // 更新缩放
        function updateZoom() {
            try {
                document.getElementById('zoomLevel').textContent = `${currentZoom}%`;
                const container = document.getElementById('previewContainer');
                const scale = currentZoom / 100;
                
                // 计算缩放后的尺寸
                container.style.transform = `scale(${scale})`;
                
                // 调整容器位置以保持居中
                const originalWidth = container.offsetWidth;
                const originalHeight = container.offsetHeight;
                const scaledWidth = originalWidth * scale;
                const scaledHeight = originalHeight * scale;
                
                // 计算位置偏移
                const offsetX = (originalWidth - scaledWidth) / 2;
                const offsetY = (originalHeight - scaledHeight) / 2;
                
                container.style.margin = `${offsetY}px auto 0`;
                
                // 重新计算页数
                calculatePages();
            } catch (error) {
                console.error('更新缩放失败:', error);
            }
        }

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (!document.getElementById('previewModal').classList.contains('hidden')) {
                updateZoom();
            }
        });

        // 打印文本
        async function printText() {
            const text = document.getElementById('text').value;
            if (!text.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入文本',
                    text: '请输入要打印的文本内容'
                });
                return;
            }

            try {
                const formData = new FormData();
                formData.append('text', text);
                formData.append('fontSize', document.getElementById('fontSize').value);
                formData.append('lineHeight', document.getElementById('lineHeight').value);
                formData.append('fontFamily', getFontFamily(document.getElementById('textFont').value));
                formData.append('textAlign', document.getElementById('textAlign').value);

                const response = await fetch('/print_text', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '打印请求已发送',
                        text: '文本已发送到打印机'
                    });
                    clearText();
                } else {
                    throw new Error(result.message || '打印失败');
                }
            } catch (error) {
                console.error('打印失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '打印失败',
                    text: error.message || '发送打印请求时出错'
                });
            }
        }

        // 获取字体系列
        function getFontFamily(font) {
            const fonts = {
                'microsoft-yahei': '"Microsoft YaHei", sans-serif',
                'simsun': 'SimSun, serif',
                'simhei': 'SimHei, sans-serif',
                'kaiti': 'KaiTi, serif',
                'fangsong': 'FangSong, serif'
            };
            return fonts[font] || fonts['microsoft-yahei'];
        }

        // 监听文本输入变化
        document.getElementById('text').addEventListener('input', updatePreview);

        // 初始化预览
        document.addEventListener('DOMContentLoaded', updatePreview);

        // 确认打印
        async function confirmPrint() {
            const textArea = document.getElementById('text');
            if (!textArea || !textArea.value.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入文本',
                    text: '请输入要打印的文本内容'
                });
                return;
            }

            try {
                // 首先检查打印服务状态
                const spoolerResponse = await fetch('/spooler_status');
                const spoolerStatus = await spoolerResponse.json();
                
                if (!spoolerStatus.is_running) {
                    const result = await Swal.fire({
                        icon: 'warning',
                        title: '打印服务未运行',
                        text: '打印服务当前未运行，是否尝试重启打印服务？',
                        showCancelButton: true,
                        confirmButtonText: '重启服务',
                        cancelButtonText: '取消'
                    });

                    if (result.isConfirmed) {
                        // 显示重启中状态
                        Swal.fire({
                            title: '正在重启打印服务',
                            text: '请稍候...',
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            allowEnterKey: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });

                        try {
                            const restartResponse = await fetch('/restart_spooler', {
                                method: 'POST'
                            });
                            const restartResult = await restartResponse.json();

                            if (!restartResult.success) {
                                throw new Error('重启打印服务失败');
                            }

                            // 等待服务重启
                            await new Promise(resolve => setTimeout(resolve, 3000));

                            // 验证服务是否已重启
                            const verifyResponse = await fetch('/spooler_status');
                            const verifyStatus = await verifyResponse.json();

                            if (!verifyStatus.is_running) {
                                throw new Error('打印服务重启后仍未运行');
                            }
                        } catch (error) {
                            // 保存错误日志
                            await saveErrorLog('打印服务重启失败', error);
                            await Swal.fire({
                                icon: 'error',
                                title: '重启失败',
                                text: error.message || '重启打印服务失败，请手动重启打印服务后重试',
                                confirmButtonText: '确定'
                            });
                            return;
                        }
                    } else {
                        return;
                    }
                }

                // 检查打印机状态
                const printerResponse = await fetch('/printer_status');
                const printerStatus = await printerResponse.json();

                if (printerStatus.error || !printerStatus.is_ready) {
                    const statusMessage = printerStatus.status_messages ? printerStatus.status_messages.join(', ') : '打印机状态未知';
                    // 保存错误日志
                    await saveErrorLog('打印机未就绪', { status: printerStatus });
                    await Swal.fire({
                        icon: 'error',
                        title: '打印机未就绪',
                        text: `打印机状态: ${statusMessage}`,
                        confirmButtonText: '确定'
                    });
                    return;
                }

                const result = await Swal.fire({
                    title: '确认打印',
                    text: '是否确认发送打印请求？',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: '确认',
                    cancelButtonText: '取消'
                });

                if (!result.isConfirmed) {
                    return;
                }

                // 显示加载状态
                Swal.fire({
                    title: '正在处理',
                    text: '正在发送打印请求...',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    allowEnterKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 收集表单数据
                const formData = new FormData();
                formData.append('text', textArea.value);
                formData.append('fontSize', document.getElementById('fontSize').value);
                formData.append('lineHeight', document.getElementById('lineHeight').value);
                formData.append('fontFamily', document.getElementById('textFont').value);
                formData.append('textAlign', document.getElementById('textAlign').value);
                formData.append('paperSize', document.getElementById('paperSize').value);
                formData.append('orientation', document.getElementById('orientation').value);

                // 发送打印请求
                const response = await fetch('/print_text', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    await Swal.fire({
                        icon: 'success',
                        title: '打印请求已发送',
                        text: '文本已发送到打印机',
                        timer: 2000,
                        showConfirmButton: false
                    });
                    clearText();
                } else {
                    throw new Error(data.message || '打印失败');
                }
            } catch (error) {
                console.error('打印失败:', error);
                // 保存错误日志
                await saveErrorLog('打印请求失败', error);
                await Swal.fire({
                    icon: 'error',
                    title: '打印失败',
                    text: error.message || '发送打印请求时出错',
                    confirmButtonText: '确定',
                    showDenyButton: true,
                    denyButtonText: '查看错误日志'
                }).then((result) => {
                    if (result.isDenied) {
                        // 显示错误日志
                        showErrorLog();
                    }
                });
            }
        }

        // 保存错误日志
        async function saveErrorLog(type, error) {
            try {
                const errorData = {
                    type: type,
                    timestamp: new Date().toISOString(),
                    message: error.message || String(error),
                    details: error.stack || JSON.stringify(error),
                    browserInfo: {
                        userAgent: navigator.userAgent,
                        platform: navigator.platform,
                        language: navigator.language
                    }
                };

                const response = await fetch('/save_error_log', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(errorData)
                });

                if (!response.ok) {
                    console.error('保存错误日志失败:', await response.text());
                }
            } catch (e) {
                console.error('保存错误日志时出错:', e);
            }
        }

        // 显示错误日志
        async function showErrorLog() {
            try {
                const response = await fetch('/get_error_logs');
                const logs = await response.json();
                
                if (logs.success && logs.data.length > 0) {
                    const logContent = logs.data.map(log => {
                        return `时间: ${new Date(log.timestamp).toLocaleString()}
类型: ${log.type}
错误信息: ${log.message}
详细信息: ${log.details}
------------------------`;
                    }).join('\n');

                    await Swal.fire({
                        title: '错误日志',
                        html: `<pre style="text-align: left; max-height: 400px; overflow-y: auto;">${logContent}</pre>`,
                        width: '800px',
                        confirmButtonText: '关闭',
                        showDenyButton: true,
                        denyButtonText: '下载日志'
                    }).then((result) => {
                        if (result.isDenied) {
                            // 下载日志文件
                            const blob = new Blob([logContent], { type: 'text/plain' });
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `print_error_log_${new Date().toISOString().slice(0,10)}.txt`;
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(a);
                        }
                    });
                } else {
                    await Swal.fire({
                        icon: 'info',
                        title: '没有错误日志',
                        text: '当前没有保存的错误日志'
                    });
                }
            } catch (e) {
                console.error('获取错误日志失败:', e);
                await Swal.fire({
                    icon: 'error',
                    title: '获取日志失败',
                    text: '无法获取错误日志信息'
                });
            }
        }

        // 预览模态框中的打印按钮事件处理
        function printFromPreview(event) {
            event.preventDefault();
            closePreview();
            confirmPrint();
        }

        // 更新预览模态框中的打印按钮事件处理
        document.querySelector('#previewModal .p-4.border-t button:last-child')
            .setAttribute('onclick', 'printFromPreview(event)');

        // 显示打印故障排除指南
        function showPrintTroubleshooting() {
            window.open('/troubleshooting', '_blank');
        }
    </script>
</body>

</html> 